<?php

namespace plugin\ycMassage\app\admin\controller;

use plugin\ycMassage\app\BaseController;
use app\common\builder\FormBuilder;
use app\common\builder\ListBuilder;
use app\common\service\UploadService;
use plugin\ycMassage\app\model\MassageMchBill;
use plugin\ycMassage\app\model\MassageUserAgentBill;
use plugin\ycMassage\app\model\MassageUserChannelsBill;
use plugin\ycMassage\app\model\MassageUserDealerBill;
use plugin\ycMassage\app\model\MassageUserSalesmanBill;
use plugin\ycMassage\app\model\MassageUserTechnicianBill;
use plugin\ycMassage\app\model\MassageUserWallet;
use plugin\ycMassage\app\model\MassageWithdrawal;
use plugin\ycMassage\utils\enum\ActionIdentity;
use plugin\ycMassage\utils\enum\Examine;
use plugin\ycMassage\utils\enum\FinanceAccountChannels;
use plugin\ycMassage\utils\enum\MoneyAction;
use support\Request;
use think\facade\Db;

class WithdrawalController extends BaseController
{
    public function indexGetTable(Request $request)
    {
        $builder = new ListBuilder;
        $builder->addScreen('uid', 'input', 'UID', [
            'placeholder' => 'UID'
        ]);
        $builder->addScreen('state', 'select', '状态', [
            'placeholder' => '提现状态',
            'options' => [
                ['label' => '未审核', 'value' => 0],
                ['label' => '已通过', 'value' => 1],
                ['label' => '已驳回', 'value' => 2],
            ],
            'clearable' => true,
        ]);
        $builder->addScreen('action', 'select', '身份', [
            'placeholder' => '身份',
            'options' => ActionIdentity::getOptions(),
            'clearable' => true,
        ]);
        $data    = $builder
            ->pageConfig()
            ->addActionOptions('操作', [
                'width' => 100
            ])
            ->addRightButton('examine', '审核', [
                'type'   => 'modal',
                'api' => $this->pluginPrefix . '/admin/Withdrawal/examine',
                'path' => '/Withdrawal/examine',
                'params' => [
                    'field' => 'state',
                    'value' => 0
                ]
            ], [
                'title'         => '订单详情',
                'style'         => [
                    'min-width' => '800px',
                    'width'     => '55%',
                ]
            ], [
                'type' => 'primary',
                'link' => true
            ])
            ->addColumn('id', '序号', [
                'width' => 100
            ])
            ->addColumn('uid', 'UID', [
                'width' => 100
            ])
            ->addColumnEle('headimg', '头像', [
                'width' => 60,
                'params' => [
                    'type' => 'image',
                ],
            ])
            ->addColumn('nickname', '用户')
            ->addColumn('create_at', '创建时间', [
                'width' => 200
            ])
            ->addColumnEle('channels', '提现渠道', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => FinanceAccountChannels::dictOptions()
                ],
            ])
            ->addColumnEle('action', '身份', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => ActionIdentity::dictOptions()
                ],
            ])
            ->addColumn('name', '真实姓名')
            ->addColumn('mobile', '手机号')
            ->addColumn('money', '提现金额')
            ->addColumn('price_fee', '手续费')
            ->addColumn('withdrawal_fee', '费率(%)')
            ->addColumn('old_withdrawal_price', '提现前')
            ->addColumn('new_withdrawal_price', '提现后')
            ->addColumnEle('state', '状态', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => Examine::dictOptions(),
                    'style' => Examine::dictOptions('style'),
                ],
            ])
            ->create();
        return parent::successRes($data);
    }
    public function index(Request $request)
    {
        $limit = $request->get('limit', 20);
        $where = [];
        $uid = $request->get('uid');
        if ($uid) {
            $where[] = ['w.uid', '=', $uid];
        }
        $order = 'id desc';
        $state = $request->get('state');
        if ($state) {
            $where[] = ['w.state', '=', $state];
        }
        $action = $request->get('action');
        if ($action) {
            $where[] = ['w.action', '=', $action];
        }
        $where[] = ['w.saas_appid', '=', $request->saas_appid];
        $Data  = MassageWithdrawal::alias('w')->where($where)->order($order)
            ->join('MassageUser u', 'u.id = w.uid')
            ->field('w.*,u.nickname,u.headimg')
            ->paginate($limit)
            ->each(function ($item) {
                $item->nickname = base64_decode($item->nickname);
                if (strpos($item->headimg, 'http') !== 0) {
                    $item->headimg = UploadService::url($item->headimg);
                }
            })
            ->toArray();
        return parent::successRes($Data);
    }
    public function examine(Request $request)
    {
        $id    = $request->get('id');
        $where = [
            ['w.id', '=', $id]
        ];
        $model = MassageWithdrawal::where($where)->alias('w')
            ->join('MassageUser u', 'u.id = w.uid')
            ->field('w.*,u.nickname,u.headimg')->find();
        if (!$model) {
            return $this->fail('该数据不存在');
        }
        if ($request->method() == 'POST') {
            $state = $request->post('state');
            $message = $request->post('message');
            Db::startTrans();
            try {
                if ($state == Examine::NO['value']) {
                    if (empty($message)) {
                        throw new \Exception('请填写驳回理由');
                    }
                    $moeny = $model->money + $model->price_fee;
                    switch ($model->action) {
                        case ActionIdentity::TECHNICIAN['value']:
                            MassageUserTechnicianBill::increase('提现驳回：' . $message, $model->uid, $moeny);
                            break;
                        case ActionIdentity::AGENT['value']:
                            MassageUserAgentBill::increase('提现驳回：' . $message, $model->uid, $moeny);
                            break;
                        case ActionIdentity::MCH['value']:
                            MassageMchBill::increase('提现驳回：' . $message, $model->uid, $moeny);
                            break;
                        case ActionIdentity::CHANNELS['value']:
                            MassageUserChannelsBill::increase('提现驳回：' . $message, $model->uid, $moeny);
                            break;
                        case ActionIdentity::DEALER['value']:
                            MassageUserDealerBill::increase('提现驳回：' . $message, $model->uid, $moeny);
                            break;
                        case ActionIdentity::SALESMAN['value']:
                            MassageUserSalesmanBill::increase('提现驳回：' . $message, $model->uid, $moeny);
                            break;
                    }
                } else if ($state == Examine::YES['value']) {
                    switch ($model->channels) {
                        case FinanceAccountChannels::WECHAT_TRANSFER['value']:
                            throw new \Exception('暂不支持微信转账');
                            break;
                    }
                }
                $model->state = $state;
                $model->message = $message;
                $model->save();
                Db::commit();
                return $this->success('操作成功');
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
        }
        $model->qrcode = UploadService::url($model->qrcode);
        if ($model->nickname) {
            $model->nickname = base64_decode($model->nickname);
        }
        if (strpos($model->headimg, 'http') !== 0) {
            $model->headimg = UploadService::url($model->headimg);
        }
        # 渲染页面
        $builder = new FormBuilder;
        $builder->setMethod('POST');
        # 取消按钮
        $builder->setConf('resetBtn', []);
        # 设置表单列
        $builder->addDivider('用户信息');
        $builder->addComponent('uid', 'info', 'UID', '', [
            'col'           => 4,
        ]);
        $builder->addComponent('headimg', 'el-avatar', '头像', '', [
            'col'           => 6,
            'props'         => [
                'src'       => $model->headimg,
                'width'     => 50,
                'height'    => 50
            ]
        ]);
        $builder->addComponent('nickname', 'info', '用户', '', [
            'col'           => 6,
        ]);
        $builder->addDivider('账户信息');
        $builder->addComponent('mobile', 'info', '联系方式', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('name', 'info', '收款人', '', [
            'col'           => 6,
        ]);
        switch ($model->channels) {
            case FinanceAccountChannels::ALIPAY_PAYMENT_CODE['value']:
            case FinanceAccountChannels::WECHAT_PAYMENT_CODE['value']:
                $builder->addComponent('qrcode', 'el-image', '收款码', '', [
                    'col'           => 6,
                    'props'         => [
                        'src'       => $model->qrcode,
                        'width'     => 160,
                        'height'    => 220
                    ]
                ]);
                break;
            case FinanceAccountChannels::WECHAT_TRANSFER['value']:
                $builder->addComponent('openid', 'info', '公众号OpenID', '', [
                    'col'           => 12,
                ]);
                $builder->addComponent('mp_openid', 'info', '小程序OpenID', '', [
                    'col'           => 12,
                ]);
                break;
            case FinanceAccountChannels::BANK_TRANSFER['value']:
                $builder->addComponent('bank', 'info', '开户行', '', [
                    'col'           => 6,
                ]);
                $builder->addComponent('account', 'info', '账号', '', [
                    'col'           => 6,
                ]);
                break;
        }
        $builder->addDivider('提现信息');
        $builder->addComponent('id', 'info', '提现ID', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('money', 'el-tag', '提现金额', '', [
            'col'           => 6,
            'props'         => [
                'type'      => 'error'
            ],
            'children'      => [
                "￥{$model->money}"
            ]
        ]);
        $builder->addComponent('price_fee', 'el-tag', '手续费', '', [
            'col'           => 6,
            'props'         => [
                'type'      => 'error'
            ],
            'children'      => [
                "￥{$model->price_fee}"
            ]
        ]);
        $builder->addComponent('withdrawal_fee', 'el-tag', '费率', '', [
            'col'           => 6,
            'props'         => [
                'type'      => 'error'
            ],
            'children'      => [
                "{$model->withdrawal_fee}%"
            ]
        ]);
        if ($model->state === 0) {
            $builder->addDivider('审核结果');
            $builder->addRow('state', 'radio', '审核', '', [
                'col'                   => [
                    'span'              => 24
                ],
                'options'       => Examine::getOptions()
            ]);
            $builder->addRow('message', 'textarea', '驳回理由', '', [
                'col'           => 24,
            ]);
        } else {
            $builder->setConf('submitBtn', []);
        }

        # 设置表单数据
        $builder->setFormData($model->toArray());
        # 生成表单规则
        $data = $builder->create();
        return $this->successRes($data);
    }
}
